<template>
  <div class="order-table-container">
    <!-- 设备table -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="卡号/手机号" prop="keywords">
        <el-input
          v-model="queryParams.keywords"
          placeholder="请输入卡号/手机号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="日期范围" prop="keywords">
        <el-date-picker
          style="width: 240px"
          v-model="baseDateArr"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-download" size="mini" @click="exportData"
          >导出</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="tableList">
      <el-table-column label="订单id" prop="rechargeFlowId" width="180" />
      <el-table-column label="手机号" prop="phone" width="130" />
      <el-table-column label="订单编号" prop="orderNo" />
      <el-table-column label="订单生成时间" prop="orderCreateTime" />
      <el-table-column label="支付金额(元)" prop="payAmount">
        <template slot-scope="scope">
          <span>{{ scope.row.payAmount / 100 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款金额(元)" prop="refundAmount">
        <template slot-scope="scope">
          <span>{{ scope.row.refundAmount / 100 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="付款方式" prop="payType" width="150">
        <template slot-scope="scope">
          <span>{{ payTypeMap[scope.row.payType] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="200"
      >
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-finance"
            @click="showRefundModal(scope.row)"
            >退款</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      :page-sizes="[10, 20, 30, 50, 500, 1000]"
    />

    <!-- 退款 弹窗 -->
    <el-dialog title="退款" :visible.sync="refundVisible" width="400px">
      <el-form
        ref="refundForm"
        :model="refundForm"
        :rules="refundRules"
        label-width="120px"
      >
        <el-form-item label="金额(元)" prop="balance">
          <el-input v-model="refundForm.balance" placeholder="请输入金额(元)" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRefundForm">确 定</el-button>
        <el-button @click="refundVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserChargingAPI, refundAPI } from "@/api/charge/order";
import moment from "moment";
import { exportExcel, exportExcelFromAPI } from "@/utils/utils";

export default {
  name: "Order",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      tableList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      editVisible: false,
      // 是否显示弹出层（数据权限）
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],

      payTypeMap: {
        WECHAT: "微信支付",
        ALIPAY: "支付宝支付",
        WALLET: "钱包",
        PHYSICAL_CARD: "实体卡支付",
      },
      chargingStatusMap: {
        FINISH: "已完成",
        CHARGING: "充电中",
        NO_PLUGGED: "未插电",
      },

      // 站点搜索关键词
      keywords: "",
      curSiteId: "",

      // 查询参数
      queryParams: {
        orderType: "RECHARGE",
        pageNum: 1,
        pageSize: 10,
        keywords: "",
      },
      baseDateArr: [
        moment().add(-1, "months").format("yyyy-MM-DD"),
        moment().format("yyyy-MM-DD"),
      ],
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        siteId: [{ required: true, message: "请输入站点id", trigger: "blur" }],
      },

      // 设备收费模式
      chargeForm: {},

      // 全部站点列表
      siteList: [],

      stationData: {},

      refundForm: {},
      refundVisible: false,
      refundRules: {
        balance: [
          { required: true, message: "请输入金额(元)", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  watch: {
    curSiteId() {
      this.getList();
    },
  },
  methods: {
    // 展示充值弹窗
    showRefundModal(item) {
      this.refundForm = {
        rechargeFlowId: item.rechargeFlowId,
        refundAmount: 0,
      };
      this.resetForm("refundForm");
      this.refundVisible = true;
    },
    // 退款表单提交
    submitRefundForm() {
      this.$refs["refundForm"].validate((valid) => {
        if (valid) {
          refundAPI({
            id: this.refundForm.rechargeFlowId,
            refundAmount: this.refundForm.balance * 100, // 单位为元
          }).then((res) => {
            this.$modal.msgSuccess("退款成功");
            this.refundVisible = false;
            this.getList();
          });
        }
      });
    },
    exportData() {
      exportExcelFromAPI("/order/wallet/record/export", {
        ...this.queryParams,
        startTime:
          this.baseDateArr && this.baseDateArr[0]
            ? moment(this.baseDateArr[0]).format("YYYY-MM-DD HH:mm:ss")
            : "",
        endTime:
          this.baseDateArr && this.baseDateArr[1]
            ? moment(this.baseDateArr[1])
                .endOf("days")
                .format("YYYY-MM-DD HH:mm:ss")
            : "",
        cardTypeList: ["VIRTUAL"],
        pageNum: 1,
        pageSize: 10000,
      });
      return false;
      exportExcel({
        data: this.formatTableList(this.tableList),
        headers: [
          { label: "订单id", key: "rechargeFlowId" },
          { label: "手机号", key: "phone" },
          { label: "订单编号", key: "cardNo" },
          { label: "订单生成时间", key: "orderCreateTime" },
          { label: "支付金额(元)", key: "payAmount" },
          { label: "退款金额(元)", key: "refundAmount" },
          { label: "付款方式", key: "payType" },
        ],
        filename: "实体卡充值(用户充值)数据.xlsx",
      });
    },
    // 格式化表格数据
    formatTableList(data) {
      return data.map((item) => {
        return {
          ...item,
          payAmount: item.payAmount / 100,
          refundAmount: item.refundAmount / 100,
          payType: this.payTypeMap[item.payType],
          chargeStatus: this.chargingStatusMap[item.chargeStatus],
        };
      });
    },
    // 编辑成功回调
    onEditSuccess() {
      this.editVisible = false;
      this.getList();
    },
    // 编辑关闭回调
    onEditCancel() {
      this.editVisible = false;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      getUserChargingAPI({
        startTime:
          this.baseDateArr && this.baseDateArr[0]
            ? moment(this.baseDateArr[0]).format("YYYY-MM-DD HH:mm:ss")
            : "",
        endTime:
          this.baseDateArr && this.baseDateArr[1]
            ? moment(this.baseDateArr[1])
                .endOf("days")
                .format("YYYY-MM-DD HH:mm:ss")
            : "",
        cardTypeList: ["VIRTUAL"],
        ...this.queryParams,
      }).then((res) => {
        this.tableList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm("确认删除吗？")
        .then(function () {
          return deleteAPI([row.id]);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 跳转详情页 */
    toDetail(row) {
      this.$router.push({
        path: "station/edit",
        query: {
          stationName: row.stationName,
        },
      });
    },
  },
};
</script>
<style scoped lang="scss">
.app-container {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;

  .site-list-container {
    width: 20%;
    flex: none;
    margin-right: 20px;

    .site-list-wrapper {
      position: relative;
      overflow: hidden;

      .site-search {
        position: absolute;
        top: 0;
        margin-bottom: 20px;
      }

      .site-list {
        margin-top: 40px;
        overflow: auto;

        .site-btn {
          width: 100%;
          font-size: 12px;
          color: #606266;
          padding: 9px 15px;
          text-align: left;
          border-radius: 2px;
          cursor: pointer;

          &:hover {
            color: #1890ff;
            background-color: #e8f4ff;
          }

          &.selected {
            color: #1890ff;
            background-color: #e8f4ff;
          }
        }
      }
    }
  }

  .station-list-container {
    width: 80%;
    flex: auto;
  }
}
</style>
